package pyf.demo11;

/**
 * @author pengyifeng
 * @version 5.1
 * @ClassName UnsafeBankDemo.java
 * @Description 模拟银行取钱 2个人同时取钱
 * @createTime 2021年07月27日 11:11:00
 */
public class UnsafeBankDemo {
    public static void main(String[] args) {
        Account account=new Account(100,"买房子的存款");
        Drawing you = new Drawing(account, 50, 0, "张三");
        Drawing girl = new Drawing(account, 100, 0, "张三的女票");
        you.start();
        girl.start();
    }
    /**
     * 账户
      */
    static class Account{
    //余额
    int money;
    //人名
    String name;

        public Account(int money, String name) {
            this.money = money;
            this.name = name;
        }
    }

    /**
     * 模拟银行钱
      */
    static class Drawing extends Thread{

    private Account account;
    private int drawingMoney;
    private int nowMoney;
    Drawing(Account account,int drawingMoney,int nowMoney,String name){
        super(name);
        this.account=account;
        this.drawingMoney=drawingMoney;
        this.nowMoney=nowMoney;
    }
    @Override
    public void run() {
        synchronized (account){
            //判断银行没有钱
            if(account.money-drawingMoney<0){
                System.out.println(Thread.currentThread().getName()+"取款余额不足:"+account.money);
                return;
            }
            //模拟取钱延时场景
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            account.money=account.money-drawingMoney;
            System.out.println(account.name + "余额为:" + account.money);
            nowMoney=nowMoney+drawingMoney;
            System.out.println(this.getName() + "手里的钱为:" + nowMoney);
        }

    }
}


}
